<template>
  <a-card :bordered="false" title="属性分组" style="min-height: 100vh">
    <a-row>
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :lg="6">
              <a-form-item label="属性名">
                <a-input v-model="attrName" placeholder="请输入属性名称" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item label="参数名">
                <a-input v-model="attrGroupName" placeholder="请输入参数名称" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="4">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button type="primary" class="button-left" @click="searchQueryAll" icon="search">查询全部</a-button>
                  <a-button type="primary" class="button-left" @click="handleAdd" icon="plus">新增</a-button>
                  <a-button type="danger" class="button-left" @click="handleDelete" icon="delete"
                            :disabled="!selectedRowKeys.length > 0">批量删除</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-row>
    <a-row>
      <a-col :span="6">
        <select-attr-component @node="selectNode"></select-attr-component>
      </a-col>
      <a-col :span="18">
        <a-table
          ref="table"
          size="middle"
          :scroll="{x:true}"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          class="j-table-force-nowrap"
          @change="handleTableChange">
          <span slot="action" slot-scope="text, record">
            <a @click="relation(record)">关联</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
                <a-popconfirm title="确定删除吗?" @confirm="() => deleteById(record.id)">
                  <a>删除</a>
                </a-popconfirm>
        </span>
        </a-table>
      </a-col>
    </a-row>
    <a-modal
      title="关联规格"
      width="40%"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-button type="primary" @click="addSpec" icon="plus">新建关联</a-button>
      <a-table
        style="margin-top: 12px"
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="specColumns"
        :dataSource="specList"
        :pagination="ipagination"
        :loading="specLoading"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
                <a-popconfirm title="确定移除吗?" @confirm="() => deleteSpec(record.id)">
                  <a>移除</a>
                </a-popconfirm>
        </span>
      </a-table>
    </a-modal>
    <a-modal
      title="选择规格"
      :visible="specVisible"
      width="40%"
      @cancel="specHandleCancel"
    >
      <template slot="footer">
        <a-button key="back" @click="specHandleCancel">
          取消
        </a-button>
        <a-popconfirm
          title="确认添加选中规格么？"
          ok-text="确认"
          cancel-text="取消"
          @confirm="specHandleOk"
        >
          <a-button key="submit" type="primary" :loading="optionalLoading">
            添加
          </a-button>
        </a-popconfirm>
      </template>
      <a-table
        style="margin-top: 12px"
        ref="table"
        :row-selection="{ selectedRowKeys: optionalRowKeys, onChange: optionalChange }"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="optionalColumns"
        :dataSource="optionalSpecList"
        :pagination="ipagination"
        :loading="specLoading"
        class="j-table-force-nowrap"
        @change="handleTableChange">
      </a-table>
    </a-modal>
    <attr-group-modal ref="modalForm" @ok="initGroupList"></attr-group-modal>
  </a-card>
</template>
<script>
import selectAttrComponent from '../../components/compents/SelectAttrComponent.vue'
import AttrGroupModal from './attr-group-modules/AttrGroupModal.vue'
import { deleteAction, getAction, postAction } from '../../api/manage'

export default {
  components: { selectAttrComponent, AttrGroupModal },
  data() {
    return {
      dataSource: [],
      attrName: null,
      record: {},
      attrGroupName: null,
      visible: false,
      optionalLoading: false,
      specVisible: false,
      nodeId: null,
      loading: false,
      specLoading: false,
      ipagination: {},
      optionalSpecList: [],
      optionalRowKeys: [],
      specList: [],
      selectedRowKeys: [],
      optionalColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '规格名称',
          align: 'center',
          dataIndex: 'attrName'
        },
        {
          title: '可选值列表',
          align: 'center',
          dataIndex: 'valueSelect'
        }
      ],
      specColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '规格名称',
          align: 'center',
          dataIndex: 'attrName'
        },
        {
          title: '可选值列表',
          align: 'center',
          dataIndex: 'valueSelect'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '组名',
          align: 'center',
          dataIndex: 'attrGroupName'
        },
        {
          title: '排序',
          align: 'center',
          dataIndex: 'sort'
        },
        {
          title: '描述',
          align: 'center',
          dataIndex: 'description'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        attributeList: '/product/attrGroup/list',
        deleteAttrGroupByIds: '/product/attrGroup/deleteBatch',
        deleteAttrGroupById: '/product/attrGroup/delete',
        getSpecList: '/product/attribute/getSpecList',
        deleteSpecById: '/product/attrAttrgroupRelation/delete',
        getOptionalSpecList: '/product/attribute/getOptionalSpecList',
        addSpecRelation: '/product/attrAttrgroupRelation/addSpecRelation'
      }
    }
  },
  methods: {
    /**
     * 分类组件选择节点
     * @param nodeId
     */
    selectNode(nodeId) {
      this.nodeId = nodeId
      this.initGroupList()
    },
    /**
     * 初始化分组列表
     */
    initGroupList() {
      this.loading = true
      getAction(this.url.attributeList, { categoryId: this.nodeId, attrGroupName: this.attrGroupName }).then(res => {
        this.dataSource = res.result.records
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 表格选择行
     */
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange() {
    },
    searchQuery() {
      this.initGroupList()
    },
    handleAdd() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    handleEdit(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    /**
     * 批量删除
     */
    handleDelete() {
      let that = this
      let ids = this.selectedRowKeys.join(',')
      console.log(ids)
      this.$confirm({
        title: '确定删除当前属性分组?',
        content: h => <div style="color:red;">删除后不可恢复</div>,
        onOk() {
          getAction(that.url.deleteCategoryById, { ids: id }).then(res => {
            if (res.success) {
              that.$message.success(res.message)
              that.initGroupList()
            } else {
              that.$message.error(res.message)
            }
          })
        },
        onCancel() {
          that.$message.info('已取消删除！')
        },
        class: 'test'
      })
    },
    /**
     * 主键删除
     */
    deleteById(id) {
      getAction(this.url.deleteAttrGroupById, { id: id }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.initGroupList()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    /**
     * 获取关联数据
     * @param record 当前行数据
     */
    relation(record) {
      this.record = record
      this.initSpecList()
      this.visible = true
    },
    /**
     * 初始化规格列表
     */
    initSpecList() {
      getAction(this.url.getSpecList, { attrGroupId: this.record.id }).then(res => {
        if (res.success) {
          this.specList = res.result.records
        } else {
          this.$message.error('获取关联规格列表数据失败！')
        }
      })
    },
    /**
     * 移除关联关系
     * @param id
     */
    deleteSpec(id) {
      getAction(this.url.deleteSpecById, { id: id }).then(res => {
        if (res.success) {
          this.$message.success('移除成功！')
          this.initSpecList()
        } else {
          this.$message.success(res.message)
        }
      })
    },
    handleOk() {
      this.visible = false
    },
    handleCancel() {
      this.visible = false
    },
    /**
     * 添加关联关系
     */
    addSpec() {
      this.specVisible = true
      this.initOptionalSpecList()
    },
    initOptionalSpecList() {
      getAction(this.url.getOptionalSpecList, { attrGroupId: this.record.id }).then(res => {
        if (res.success) {
          this.optionalSpecList = res.result.records
        } else {
          this.$message.error('查询规格列表失败！')
        }
      })
    },
    optionalChange(selectedRowKeys) {
      this.optionalRowKeys = selectedRowKeys
    },
    specHandleOk() {
      this.optionalLoading = true
      let param = {
        attributeIds: this.optionalRowKeys,
        groupId: this.record.id
      }
      postAction(this.url.addSpecRelation, param).then(res => {
        if (res.success) {
          this.$message.info('关联规格成功！')
          this.initSpecList()
        }
      }).finally(() => {
        this.optionalLoading = false
        this.specVisible = false
      })
    },
    specHandleCancel() {
      this.specVisible = false
    }
  }

}
</script>
<style>
@import '/src/assets/less/common.less';

.button-left {
  margin-left: 8px;
}
</style>